<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>蓝天驾校 - 后台管理系统</title>
    <style>
        :root {
            --primary-color: #e1f5fe;
            --secondary-color: #4fc3f7;
            --accent-color: #0288d1;
            --text-color: #333;
            --light-color: #ffffff;
            --sidebar-color: #01579b;
        }

        body {
            font-family: 'Microsoft YaHei', sans-serif;
            margin: 0;
            padding: 0;
            color: var(--text-color);
            background-color: var(--light-color);
        }

        .container {
            display: flex;
            min-height: 100vh;
        }

        .sidebar {
            width: 250px;
            background-color: var(--sidebar-color);
            color: var(--light-color);
            padding: 20px 0;
        }

        .sidebar-header {
            padding: 0 20px 20px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }

        .sidebar-menu {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .sidebar-menu li {
            padding: 12px 20px;
            cursor: pointer;
            transition: background-color 0.3s;
        }

        .sidebar-menu li:hover,
        .sidebar-menu li.active {
            background-color: var(--accent-color);
        }

        .main-content {
            flex: 1;
            padding: 20px;
            background-color: var(--primary-color);
        }

        .content-header {
            background-color: var(--light-color);
            padding: 15px 20px;
            margin-bottom: 20px;
            border-radius: 5px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        }

        .card {
            background-color: var(--light-color);
            border-radius: 5px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        }

        table {
            width: 100%;
            border-collapse: collapse;
        }

        th,
        td {
            padding: 12px 15px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }

        th {
            background-color: var(--primary-color);
            font-weight: bold;
            color: var(--accent-color);
        }

        tr:hover {
            background-color: rgba(79, 195, 247, 0.1);
        }

        .form-group {
            margin-bottom: 15px;
        }

        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: var(--accent-color);
        }

        input,
        select,
        textarea {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
            background-color: var(--light-color);
        }

        textarea {
            min-height: 100px;
        }

        .btn {
            padding: 10px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.3s;
        }

        .btn-primary {
            background-color: var(--accent-color);
            color: var(--light-color);
        }

        .btn-danger {
            background-color: #e53935;
            color: var(--light-color);
        }

        .btn-success {
            background-color: #43a047;
            color: var(--light-color);
        }

        .tab-container {
            margin-bottom: 20px;
        }

        .tab-nav {
            display: flex;
            border-bottom: 1px solid #ddd;
        }

        .tab-nav button {
            padding: 10px 20px;
            background: none;
            border: none;
            cursor: pointer;
            border-bottom: 3px solid transparent;
            color: var(--text-color);
            transition: all 0.3s;
        }

        .tab-nav button:hover {
            color: var(--accent-color);
        }

        .tab-nav button.active {
            border-bottom-color: var(--accent-color);
            color: var(--accent-color);
            font-weight: bold;
        }

        .tab-content {
            display: none;
            padding: 20px 0;
        }

        .tab-content.active {
            display: block;
        }

        @media (max-width: 768px) {
            .container {
                flex-direction: column;
            }

            .sidebar {
                width: 100%;
            }

            .tab-nav {
                overflow-x: auto;
                white-space: nowrap;
            }
        }

        /* ---查看的弹出窗样式--- */

        .modal-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.6);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
            /* 默认隐藏，由JS控制显示 */
            display: none;
        }

        .modal-content {
            background-color: var(--light-color);
            padding: 20px 30px;
            border-radius: 8px;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
            width: 90%;
            max-width: 500px;
            position: relative;
            animation: fadeIn 0.3s ease-out;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(-20px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid #ddd;
            padding-bottom: 10px;
            margin-bottom: 20px;
        }

        .modal-header h2 {
            margin: 0;
            color: var(--accent-color);
        }

        .modal-close {
            font-size: 28px;
            font-weight: bold;
            color: #aaa;
            cursor: pointer;
            transition: color 0.2s;
        }

        .modal-close:hover {
            color: #333;
        }

        .modal-body .form-group {
            margin-bottom: 20px;
        }

        .modal-body .form-group label {
            color: var(--sidebar-color);
            font-size: 14px;
            margin-bottom: 8px;
        }

        .modal-body .form-group p {
            margin: 0;
            padding: 8px;
            background-color: var(--primary-color);
            border-radius: 4px;
            font-size: 16px;
            min-height: 20px;
        }

        .modal-footer {
            text-align: right;
            margin-top: 20px;
        }

        /* --- CSS代码结束 --- */
    </style>
</head>

<body>
    <div class="container">
        <div class="sidebar">
            <div class="sidebar-header">
                <h2>蓝天驾校</h2>
                <p>后台管理系统</p>
            </div>
            <ul class="sidebar-menu">
                <li class="active">基本信息管理</li>
                <li>学员管理</li>
                <li>教练管理</li>
                <li>课程管理</li>
                <li>财务管理</li>
                <li>系统设置</li>
                <li><a href="/zrz/daohanglanLayui">退出</a></li>
            </ul>
        </div>

        <div class="main-content">
            <div class="content-header">
                <h1>基本信息管理</h1>
            </div>

            <div class="tab-container">
                <div class="tab-nav">
                    <button class="active" onclick="switchTab('school-info')">驾校信息</button>
                    <button onclick="switchTab('student-reg')">学员报名</button>
                    <button onclick="switchTab('course-mgt')">班型管理</button>
                    <button onclick="switchTab('announcement')">公告与优惠</button>
                </div>

                <div id="school-info" class="tab-content active">
                    <div class="card">
                        <h2 style="color: var(--accent-color);">驾校基本信息</h2>
                        <form id="schoolForm">
                            <div class="form-group">
                                <label for="school-name">驾校名称</label>
                                <input type="text" id="school-name" name="schoolName" value="">
                            </div>
                            <div class="form-group">
                                <label for="school-address">地址</label>
                                <input type="text" id="school-address" name="address" value="">
                            </div>
                            <div class="form-group">
                                <label for="school-phone">联系电话</label>
                                <input type="tel" id="school-phone" name="phoneNumber" value="">
                            </div>
                            <div class="form-group">
                                <label for="school-hours">营业时间</label>
                                <input type="text" id="school-hours" name="operationTime" value="">
                            </div>
                            <div class="form-group">
                                <label for="school-desc">驾校简介</label>
                                <textarea id="school-desc" name="description"></textarea>
                            </div>
                            <button type="submit" class="btn btn-primary">保存更改</button>
                        </form>
                    </div>
                </div>

                <div id="student-reg" class="tab-content">
                    <div class="card">
                        <h2 style="color: var(--accent-color);">学员报名信息</h2>
                        <div style="overflow-x: auto;">
                            <table id="studentTable">
                                <thead>
                                    <tr>
                                        <th>序号</th>
                                        <th>姓名</th>
                                        <th>手机号</th>
                                        <th>身份证号</th>
                                        <th>班型</th>
                                        <th>驾照类型</th>
                                        <th>报名时间</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="studentTableBody"></tbody>
                            </table>
                        </div>
                        <div
                            style="margin-top: 15px; display: flex; justify-content: space-between; align-items: center;">
                            <div>
                                <label for="pageSize">每页显示:</label>
                                <select id="pageSize" onchange="loadStudentData(1, this.value)">
                                    <option value="5">5</option>
                                    <option value="10" selected>10</option>
                                    <option value="20">20</option>
                                </select>
                                <button class="btn btn-primary" style="margin-left: 8px;"
                                    onclick="loadStudentData(1, document.getElementById('pageSize').value)">刷新</button>
                            </div>
                            <div id="pagination-nav">
                            </div>
                        </div>
                    </div>
                </div>
                <!-- 查看报名信息的模态窗口 -->
                <div id="viewStudentModal" class="modal-overlay">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h2>学员详细信息</h2>
                            <span class="modal-close" onclick="closeStudentModal()">&times;</span>
                        </div>
                        <div class="modal-body">
                            <div class="form-group">
                                <label>姓名:</label>
                                <p id="modal-student-name"></p>
                            </div>
                            <div class="form-group">
                                <label>手机号:</label>
                                <p id="modal-student-phone"></p>
                            </div>
                            <div class="form-group">
                                <label>身份证号:</label>
                                <p id="modal-student-idCard"></p>
                            </div>
                            <div class="form-group">
                                <label>所选班型:</label>
                                <p id="modal-student-classType"></p>
                            </div>
                            <div class="form-group">
                                <label>驾照类型:</label>
                                <p id="modal-student-licenseType"></p>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button class="btn btn-primary" onclick="closeStudentModal()">关闭</button>
                        </div>
                    </div>
                </div>
                <!-- 班型管理 -->
                <div id="course-mgt" class="tab-content">
                    <div class="card">
                        <h2 style="color: var(--accent-color);">班型管理</h2>

                        <div style="display: flex; gap: 15px; margin-bottom: 20px; align-items: center;">
                            <!-- <input type="text" id="course-search-name" placeholder="按班型名称搜索..." style="width: 200px;">
                            <select id="course-search-status" style="width: 150px;">
                                <option value="">所有状态</option>
                                <option value="启用">启用</option>
                                <option value="停用">停用</option>
                            </select>
                            <button class="btn btn-primary" onclick="searchCourses()">搜索</button> -->
                            <button class="btn btn-success" onclick="openCourseModal()">新增班型</button>
                        </div>

                        <div style="overflow-x: auto;">
                            <table id="courseTable">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>班型名称</th>
                                        <th>描述</th>
                                        <th>价格 (¥)</th>
                                        <th>包含服务</th>
                                        <th>状态</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="courseTableBody">
                                </tbody>
                            </table>
                        </div>

                        <div id="course-pagination-nav"
                            style="margin-top: 15px; display: flex; justify-content: flex-end; align-items: center;">
                        </div>
                    </div>
                </div>

                <div id="courseModal" class="modal-overlay">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h2 id="courseModalTitle">新增班型</h2>
                            <span class="modal-close" onclick="closeCourseModal()">&times;</span>
                        </div>
                        <form id="courseForm" onsubmit="event.preventDefault(); saveCourse();">
                            <div class="modal-body">
                                <input type="hidden" id="course-id">
                                <div class="form-group">
                                    <label for="course-name">班型名称</label>
                                    <input type="text" id="course-name" required>
                                </div>
                                <div class="form-group">
                                    <label for="course-price">价格</label>
                                    <input type="number" id="course-price" step="0.01" required>
                                </div>
                                <div class="form-group">
                                    <label for="course-status">状态</label>
                                    <select id="course-status" required>
                                        <option value="启用">启用</option>
                                        <option value="停用">停用</option>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label for="course-description">描述</label>
                                    <textarea id="course-description"></textarea>
                                </div>
                                <div class="form-group">
                                    <label for="course-services">包含服务</label>
                                    <textarea id="course-services"></textarea>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn" onclick="closeCourseModal()"
                                    style="background-color:#ccc;">取消</button>
                                <button type="submit" class="btn btn-primary">保存</button>
                            </div>
                        </form>
                    </div>
                </div>

                <div id="announcement" class="tab-content">
                    <div class="card">
                        <h2 style="color: var(--accent-color);">公告与优惠信息管理</h2>

                        <div style="display: flex; gap: 15px; margin-bottom: 20px; align-items: center;">
                            <!-- <input type="text" id="announcement-search-title" placeholder="按标题搜索..." style="width: 200px;">
                            <select id="announcement-search-status" style="width: 150px;">
                                <option value="">所有状态</option>
                                <option value="已发布">已发布</option>
                                <option value="已下线">已下线</option>
                                <option value="草稿">草稿</option>
                            </select>
                            <button class="btn btn-primary" onclick="searchAnnouncements()">搜索</button> -->
                            <button class="btn btn-success" onclick="openAnnouncementModal()">新增公告</button>
                        </div>

                        <div style="overflow-x: auto;">
                            <table id="announcementTable">
                                <thead>
                                    <tr>
                                        <th>ID</th>
                                        <th>标题</th>
                                        <th style="width: 40%;">内容</th>
                                        <th>发布时间</th>
                                        <th>状态</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="announcementTableBody">
                                </tbody>
                            </table>
                        </div>

                        <div id="announcement-pagination-nav"
                            style="margin-top: 15px; display: flex; justify-content: flex-end; align-items: center;">
                        </div>
                    </div>
                </div>

                <div id="announcementModal" class="modal-overlay">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h2 id="announcementModalTitle">新增公告</h2>
                            <span class="modal-close" onclick="closeAnnouncementModal()">&times;</span>
                        </div>
                        <form id="announcementForm" onsubmit="event.preventDefault(); saveAnnouncement();">
                            <div class="modal-body">
                                <input type="hidden" id="announcement-id">
                                <div class="form-group">
                                    <label for="announcement-title">标题</label>
                                    <input type="text" id="announcement-title" required>
                                </div>
                                <div class="form-group">
                                    <label for="announcement-status">状态</label>
                                    <select id="announcement-status" required>
                                        <option value="已发布">已发布</option>
                                        <option value="已下线">已下线</option>
                                        <option value="草稿">草稿</option>
                                    </select>
                                </div>
                                <div class="form-group">
                                    <label for="announcement-publish-date">发布时间</label>
                                    <input type="datetime-local" id="announcement-publish-date" required>
                                </div>
                                <div class="form-group">
                                    <label for="announcement-content">内容</label>
                                    <textarea id="announcement-content" rows="5"></textarea>
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn" onclick="closeAnnouncementModal()"
                                    style="background-color:#ccc;">取消</button>
                                <button type="submit" class="btn btn-primary">保存</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>

        let g_currentAnnouncementPageNum = 1;
        let g_currentPageNum = 1;
        let g_currentCoursePageNum = 1;
        function switchTab(tabId) {
            document.querySelectorAll('.tab-content').forEach(tab => {
                tab.classList.remove('active');
            });
            document.querySelectorAll('.tab-nav button').forEach(btn => {
                btn.classList.remove('active');
            });
            document.getElementById(tabId).classList.add('active');
            event.currentTarget.classList.add('active');
        }

        document.addEventListener('DOMContentLoaded', function () {
            loadSchoolInfo(8);  // 默认加载 id=8 的驾校数据
            loadStudentData(1, 10); // 默认加载前 10 条注册信息
            // 新增：首次加载课程数据
            loadCoursesData(1);
            // 新增：首次加载公告数据
            loadAnnouncementsData(1);
        });

        // 新的：加载学员数据并更新全局变量
        function loadStudentData(pageNum = 1, pageSize = 10) {
            g_currentPageNum = pageNum; // 更新全局当前页码

            const selectedPageSize = document.getElementById('pageSize').value;

            fetch(`/api/drivingSchoolRegistration?pageNum=${pageNum}&pageSize=${selectedPageSize}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应错误');
                    }
                    return response.json();
                })
                .then(data => {
                    if (data && data.list) {
                        g_currentPageItemCount = data.size; // 更新当前页的实际项目数量
                        renderStudentTableAndPagination(data);
                    } else {
                        g_currentPageItemCount = 0;
                        const tbody = document.getElementById('studentTableBody');
                        tbody.innerHTML = `<tr><td colspan="8" style="text-align: center;">未能加载学员信息。</td></tr>`;
                        document.getElementById('pagination-nav').innerHTML = '';
                    }
                })
                .catch(error => {
                    g_currentPageItemCount = 0;
                    console.error('加载学员数据时出错:', error);
                    const tbody = document.getElementById('studentTableBody');
                    tbody.innerHTML = `<tr><td colspan="8" style="text-align: center;">加载失败，请检查网络或联系管理员。</td></tr>`;
                    document.getElementById('pagination-nav').innerHTML = '';
                    alert('加载学员数据失败！');
                });
        }

        // 新的：渲染表格和分页导航
        function renderStudentTableAndPagination(data) {
            const { list, total, pageNum, pageSize, pages, hasPreviousPage, hasNextPage, navigatepageNums } = data;

            // 1. 渲染表格内容
            const tbody = document.getElementById('studentTableBody');
            if (!list || list.length === 0) {
                tbody.innerHTML = `<tr><td colspan="8" style="text-align: center;">暂无学员信息</td></tr>`;
            } else {
                tbody.innerHTML = list.map((student, index) => `
            <tr>
                <td>${(pageNum - 1) * pageSize + index + 1}</td>
                <td>${student.name || 'N/A'}</td>
                <td>${student.phoneNumber || 'N/A'}</td>
                <td>${student.idCard || 'N/A'}</td>
                <td>${student.classType || 'N/A'}</td>
                <td>${student.licenseType || 'N/A'}</td>
                <td>${new Date().toLocaleDateString()}</td> <td>
                    <button class="btn btn-primary" onclick="editStudent('${student.id}')">查看</button>
                    <button class="btn btn-danger" onclick="deleteStudent('${student.id}')">删除</button>
                </td>
            </tr>
        `).join('');
            }

            // 2. 渲染分页导航控件
            const paginationContainer = document.getElementById('pagination-nav');
            let paginationHtml = '';

            // 信息展示
            paginationHtml += `<span style="margin-right: 15px; color: var(--text-color);">共 ${total} 条 / ${pages} 页</span>`;

            // “上一页”按钮
            paginationHtml += `<button class="btn btn-primary" style="margin-right: 5px;" ${!hasPreviousPage ? 'disabled' : ''} onclick="loadStudentData(${pageNum - 1})">上一页</button>`;

            // 页码按钮
            navigatepageNums.forEach(pNum => {
                if (pNum === pageNum) {
                    // 当前页，使用不同的样式并禁用
                    paginationHtml += `<button class="btn" style="margin: 0 2px; background-color: var(--accent-color); color: var(--light-color);" disabled>${pNum}</button>`;
                } else {
                    // 其他页码
                    paginationHtml += `<button class="btn btn-primary" style="margin: 0 2px; background-color: var(--light-color); color: var(--accent-color); border: 1px solid var(--accent-color);" onclick="loadStudentData(${pNum})">${pNum}</button>`;
                }
            });

            // “下一页”按钮
            paginationHtml += `<button class="btn btn-primary" style="margin-left: 5px;" ${!hasNextPage ? 'disabled' : ''} onclick="loadStudentData(${pageNum + 1})">下一页</button>`;

            paginationContainer.innerHTML = paginationHtml;
        }

        // 重写 editStudent 函数，用于获取并显示学员详情
        // 注意：此函数名为 editStudent 以匹配您按钮的 onclick 事件，但其功能是“查看”。
        function editStudent(idCard) {
            if (!idCard) {
                alert('无效的学员信息！');
                return;
            }

            // 显示加载提示（可选）
            const modal = document.getElementById('viewStudentModal');
            const nameField = document.getElementById('modal-student-name');
            nameField.textContent = '正在加载...';
            // 清空其他字段
            document.getElementById('modal-student-phone').textContent = '';
            document.getElementById('modal-student-idCard').textContent = '';
            document.getElementById('modal-student-classType').textContent = '';
            document.getElementById('modal-student-licenseType').textContent = '';

            modal.style.display = 'flex'; // 先显示弹窗框架

            // 从后端API获取学员数据
            fetch(`/api/drivingSchoolRegistration/${idCard}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`网络错误 (状态码: ${response.status})`);
                    }
                    return response.json();
                })
                .then(student => {
                    // 将获取到的数据填充到弹窗中
                    if (student) {
                        nameField.textContent = student.name || '无';
                        document.getElementById('modal-student-phone').textContent = student.phoneNumber || '无';
                        document.getElementById('modal-student-idCard').textContent = student.idCard || '无';
                        document.getElementById('modal-student-classType').textContent = student.classType || '无';
                        document.getElementById('modal-student-licenseType').textContent = student.licenseType || '无';
                    } else {
                        nameField.textContent = '未找到该学员信息。';
                    }
                })
                .catch(error => {
                    console.error('获取学员详细信息失败:', error);
                    alert('获取学员详细信息失败，请稍后重试。');
                    nameField.textContent = '加载失败。';
                });
        }

        // 新增：关闭弹窗的函数
        function closeStudentModal() {
            document.getElementById('viewStudentModal').style.display = 'none';
        }

        // (保留您已有的其他JS函数，如 deleteStudent, loadCourses 等)


        // 新的：真实的删除函数
        function deleteStudent(idCard) {
            if (!idCard) {
                alert('无效的学员信息，无法删除！');
                return;
            }

            // 步骤 1: 弹窗确认
            if (confirm(`您确定要删除身份证号为 ${idCard} 的学员吗？\n此操作将永久删除数据，无法撤销。`)) {

                // 步骤 2: 调用后端 DELETE API
                fetch(`/api/drivingSchoolRegistration/${idCard}`, {
                    method: 'DELETE'
                })
                    .then(response => {
                        if (response.ok) {
                            alert('删除成功！');

                            // 步骤 3: 智能刷新列表
                            // 如果当前页只剩一条数据，并且不是第一页，那么删除后就请求前一页的数据
                            if (g_currentPageItemCount === 1 && g_currentPageNum > 1) {
                                loadStudentData(g_currentPageNum - 1);
                            } else {
                                // 否则，重新加载当前页
                                loadStudentData(g_currentPageNum);
                            }
                        } else {
                            // 处理服务器返回的错误
                            throw new Error('服务器删除失败，可能该数据已被他人删除。');
                        }
                    })
                    .catch(error => {
                        console.error('删除操作失败:', error);
                        alert('删除失败，请检查网络或联系管理员。');
                    });
            }
        }

        // 加载并回填驾校信息
        function loadSchoolInfo(id) {
            fetch(`/hzj/get/${id}`)
                .then(response => response.json())
                .then(data => {
                    if (data) {
                        document.getElementById('school-name').value = data.schoolName || '';
                        document.getElementById('school-address').value = data.address || '';
                        document.getElementById('school-phone').value = data.phoneNumber || '';
                        document.getElementById('school-hours').value = data.operationTime || '';
                        document.getElementById('school-desc').value = data.description || '';
                    } else {
                        alert('未找到对应驾校信息！');
                    }
                })
                .catch(error => {
                    console.error('错误:', error);
                    alert('网络错误，加载失败！');
                });
        }

        // 保存驾校信息到后端
        document.getElementById('schoolForm').addEventListener('submit', function (e) {
            e.preventDefault();

            const formData = {
                id: 8, // 假设默认使用 id=8
                schoolName: document.getElementById('school-name').value,
                address: document.getElementById('school-address').value,
                phoneNumber: document.getElementById('school-phone').value,
                operationTime: document.getElementById('school-hours').value,
                description: document.getElementById('school-desc').value
            };

            fetch('/hzj/save', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(formData)
            })
                .then(response => response.json())
                .then(data => {
                    if (data > 0) {
                        alert('驾校信息保存成功！');
                    } else {
                        alert('保存失败，请稍后重试！');
                    }
                })
                .catch(error => {
                    console.error('错误:', error);
                    alert('网络错误，请稍后重试！');
                });
        });

        /**
 * 加载课程数据（分页 + 条件查询）
 * @param {number} pageNum - 要加载的页码
 * @param {object} params - 查询参数对象
 */
        function loadCoursesData(pageNum = 1, params = {}) {
            g_currentCoursePageNum = pageNum;
            const pageSize = 10; // 或从页面上的下拉框获取

            // 构建查询字符串
            const query = new URLSearchParams({
                pageNum: pageNum,
                pageSize: pageSize,
                ...params
            }).toString();

            fetch(`/api/courses?${query}`)
                .then(response => response.json())
                .then(data => {
                    renderCourseTableAndPagination(data);
                })
                .catch(error => {
                    console.error('加载课程数据失败:', error);
                    document.getElementById('courseTableBody').innerHTML = `<tr><td colspan="7" style="text-align:center;">加载课程数据失败</td></tr>`;
                });
        }

        /**
         * 渲染课程表格和分页控件
         * @param {object} pageInfo - 从后端获取的PageInfo对象
         */
        function renderCourseTableAndPagination(pageInfo) {
            const tbody = document.getElementById('courseTableBody');
            const { list, total, pageNum, pages, hasPreviousPage, hasNextPage, navigatepageNums } = pageInfo;

            // 渲染表格
            if (!list || list.length === 0) {
                tbody.innerHTML = `<tr><td colspan="7" style="text-align:center;">暂无班型数据</td></tr>`;
            } else {
                tbody.innerHTML = list.map(course => `
            <tr>
                <td>${course.id}</td>
                <td>${course.name || ''}</td>
                <td>${course.description || ''}</td>
                <td>${course.price != null ? course.price.toFixed(2) : '0.00'}</td>
                <td>${course.includedServices || ''}</td>
                <td>${course.status || ''}</td>
                <td>
                    <button class="btn btn-primary" onclick="openCourseModal(${course.id})">编辑</button>
                    <button class="btn btn-danger" onclick="deleteCourse(${course.id})">删除</button>
                </td>
            </tr>
        `).join('');
            }

            // 渲染分页
            const paginationContainer = document.getElementById('course-pagination-nav');
            if (pages > 0) {
                let paginationHtml = `<span style="margin-right: 15px; color: var(--text-color);">共 ${total} 条 / ${pages} 页</span>`;
                paginationHtml += `<button class="btn btn-primary" ${!hasPreviousPage ? 'disabled' : ''} onclick="loadCoursesData(${pageNum - 1})">上一页</button>`;

                navigatepageNums.forEach(pNum => {
                    paginationHtml += `<button class="btn ${pNum === pageNum ? 'btn-primary' : ''}" style="margin: 0 5px;" ${pNum === pageNum ? 'disabled' : ''} onclick="loadCoursesData(${pNum})">${pNum}</button>`;
                });

                paginationHtml += `<button class="btn btn-primary" ${!hasNextPage ? 'disabled' : ''} onclick="loadCoursesData(${pageNum + 1})">下一页</button>`;
                paginationContainer.innerHTML = paginationHtml;
            } else {
                paginationContainer.innerHTML = '';
            }
        }

        /**
         * 打开新增/编辑课程的模态窗口
         * @param {number|null} id - 如果提供了ID，则为编辑模式；否则为新增模式
         */
        function openCourseModal(id = null) {
            const modal = document.getElementById('courseModal');
            const title = document.getElementById('courseModalTitle');
            const form = document.getElementById('courseForm');

            form.reset(); // 重置表单
            document.getElementById('course-id').value = '';

            if (id) {
                // 编辑模式
                title.textContent = '编辑班型';
                fetch(`/api/courses/${id}`)
                    .then(res => res.json())
                    .then(course => {
                        document.getElementById('course-id').value = course.id;
                        document.getElementById('course-name').value = course.name;
                        document.getElementById('course-description').value = course.description;
                        document.getElementById('course-price').value = course.price;
                        document.getElementById('course-services').value = course.includedServices;
                        document.getElementById('course-status').value = course.status;
                    });
            } else {
                // 新增模式
                title.textContent = '新增班型';
            }

            modal.style.display = 'flex';
        }

        /**
         * 关闭课程模态窗口
         */
        function closeCourseModal() {
            document.getElementById('courseModal').style.display = 'none';
        }

        /**
         * 保存课程（处理新增和更新）
         */
        function saveCourse() {
            const id = document.getElementById('course-id').value;
            const course = {
                name: document.getElementById('course-name').value,
                description: document.getElementById('course-description').value,
                price: document.getElementById('course-price').value,
                includedServices: document.getElementById('course-services').value,
                status: document.getElementById('course-status').value
            };

            const isUpdate = !!id;
            const url = isUpdate ? `/api/courses/${id}` : '/api/courses';
            const method = isUpdate ? 'PUT' : 'POST';

            fetch(url, {
                method: method,
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(course)
            })
                .then(response => {
                    if (response.ok) {
                        alert(isUpdate ? '更新成功！' : '新增成功！');
                        closeCourseModal();
                        loadCoursesData(g_currentCoursePageNum); // 刷新当前页
                    } else {
                        throw new Error('保存失败');
                    }
                })
                .catch(error => {
                    console.error('保存课程失败:', error);
                    alert('操作失败，请重试！');
                });
        }

        /**
         * 删除课程
         * @param {number} id - 要删除的课程ID
         */
        function deleteCourse(id) {
            if (confirm('您确定要删除这个班型吗？')) {
                fetch(`/api/courses/${id}`, { method: 'DELETE' })
                    .then(response => {
                        if (response.ok) {
                            alert('删除成功！');
                            loadCoursesData(g_currentCoursePageNum); // 智能刷新逻辑可以后续添加
                        } else {
                            throw new Error('删除失败');
                        }
                    })
                    .catch(error => {
                        console.error('删除课程失败:', error);
                        alert('删除失败，请重试！');
                    });
            }
        }

        /**
  * 加载公告数据（分页 + 条件查询）
  * @param {number} pageNum - 要加载的页码
  * @param {object} params - 查询参数对象
  */
        function loadAnnouncementsData(pageNum = 1, params = {}) {
            g_currentAnnouncementPageNum = pageNum;
            const pageSize = 10;

            const query = new URLSearchParams({
                pageNum: pageNum,
                pageSize: pageSize,
                ...params
            }).toString();

            fetch(`/api/announcements?${query}`)
                .then(response => response.json())
                .then(data => {
                    renderAnnouncementTableAndPagination(data);
                })
                .catch(error => {
                    console.error('加载公告数据失败:', error);
                    document.getElementById('announcementTableBody').innerHTML = `<tr><td colspan="6" style="text-align:center;">加载公告数据失败</td></tr>`;
                });
        }

        /**
         * 渲染公告表格和分页控件
         * @param {object} pageInfo - 从后端获取的PageInfo对象
         */
        function renderAnnouncementTableAndPagination(pageInfo) {
            const tbody = document.getElementById('announcementTableBody');
            const { list, total, pageNum, pages, hasPreviousPage, hasNextPage, navigatepageNums } = pageInfo;

            if (!list || list.length === 0) {
                tbody.innerHTML = `<tr><td colspan="6" style="text-align:center;">暂无公告</td></tr>`;
            } else {
                tbody.innerHTML = list.map(item => {
                    // 格式化日期，如果存在
                    let formattedDate = 'N/A';
                    if (item.publishDate) {
                        // 将ISO字符串转换为更友好的格式
                        formattedDate = new Date(item.publishDate).toLocaleString('zh-CN', { hour12: false });
                    }

                    return `
                <tr>
                    <td>${item.id}</td>
                    <td>${item.title || ''}</td>
                    <td>${item.content || ''}</td>
                    <td>${formattedDate}</td>
                    <td>${item.status || ''}</td>
                    <td>
                        <button class="btn btn-primary" onclick="openAnnouncementModal(${item.id})">编辑</button>
                        <button class="btn btn-danger" onclick="deleteAnnouncement(${item.id})">删除</button>
                    </td>
                </tr>
            `;
                }).join('');
            }

            // 渲染分页
            const paginationContainer = document.getElementById('announcement-pagination-nav');
            if (pages > 0) {
                let paginationHtml = `<span style="margin-right: 15px; color: var(--text-color);">共 ${total} 条 / ${pages} 页</span>`;
                paginationHtml += `<button class="btn btn-primary" ${!hasPreviousPage ? 'disabled' : ''} onclick="loadAnnouncementsData(${pageNum - 1})">上一页</button>`;

                navigatepageNums.forEach(pNum => {
                    paginationHtml += `<button class="btn ${pNum === pageNum ? 'btn-primary' : ''}" style="margin: 0 5px;" ${pNum === pageNum ? 'disabled' : ''} onclick="loadAnnouncementsData(${pNum})">${pNum}</button>`;
                });

                paginationHtml += `<button class="btn btn-primary" ${!hasNextPage ? 'disabled' : ''} onclick="loadAnnouncementsData(${pageNum + 1})">下一页</button>`;
                paginationContainer.innerHTML = paginationHtml;
            } else {
                paginationContainer.innerHTML = '';
            }
        }

        /**
         * 执行公告搜索
         */
        function searchAnnouncements() {
            const title = document.getElementById('announcement-search-title').value;
            const status = document.getElementById('announcement-search-status').value;
            const params = {};
            if (title) params.title = title;
            if (status) params.status = status;
            loadAnnouncementsData(1, params);
        }

        /**
         * 打开新增/编辑公告的模态窗口
         * @param {number|null} id - 如果提供了ID，则为编辑模式；否则为新增模式
         */
        function openAnnouncementModal(id = null) {
            const modal = document.getElementById('announcementModal');
            const title = document.getElementById('announcementModalTitle');
            const form = document.getElementById('announcementForm');

            form.reset();
            document.getElementById('announcement-id').value = '';

            if (id) {
                // 编辑模式
                title.textContent = '编辑公告';
                fetch(`/api/announcements/${id}`)
                    .then(res => res.json())
                    .then(item => {
                        document.getElementById('announcement-id').value = item.id;
                        document.getElementById('announcement-title').value = item.title;
                        document.getElementById('announcement-content').value = item.content;
                        document.getElementById('announcement-status').value = item.status;
                        // 格式化日期以便datetime-local input可以识别 (YYYY-MM-DDTHH:mm)
                        if (item.publishDate) {
                            const d = new Date(item.publishDate);
                            // toISOString()返回UTC时间，我们需要转换为本地时间并格式化
                            const localDate = new Date(d.getTime() - (d.getTimezoneOffset() * 60000));
                            document.getElementById('announcement-publish-date').value = localDate.toISOString().slice(0, 16);
                        }
                    });
            } else {
                // 新增模式
                title.textContent = '新增公告';
            }

            modal.style.display = 'flex';
        }

        /**
         * 关闭公告模态窗口
         */
        function closeAnnouncementModal() {
            document.getElementById('announcementModal').style.display = 'none';
        }

        /**
         * 保存公告（处理新增和更新）
         */
        function saveAnnouncement() {
            const id = document.getElementById('announcement-id').value;
            const announcement = {
                title: document.getElementById('announcement-title').value,
                content: document.getElementById('announcement-content').value,
                publishDate: document.getElementById('announcement-publish-date').value,
                status: document.getElementById('announcement-status').value
            };

            const isUpdate = !!id;
            const url = isUpdate ? `/api/announcements/${id}` : '/api/announcements';
            const method = isUpdate ? 'PUT' : 'POST';

            fetch(url, {
                method: method,
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(announcement)
            })
                .then(response => {
                    if (response.ok) {
                        alert(isUpdate ? '更新成功！' : '新增成功！');
                        closeAnnouncementModal();
                        loadAnnouncementsData(g_currentAnnouncementPageNum);
                    } else {
                        throw new Error('保存失败');
                    }
                })
                .catch(error => {
                    console.error('保存公告失败:', error);
                    alert('操作失败，请重试！');
                });
        }

        /**
         * 删除公告
         * @param {number} id - 要删除的公告ID
         */
        function deleteAnnouncement(id) {
            if (confirm('您确定要删除这条公告吗？')) {
                fetch(`/api/announcements/${id}`, { method: 'DELETE' })
                    .then(response => {
                        if (response.ok) {
                            alert('删除成功！');
                            loadAnnouncementsData(g_currentAnnouncementPageNum);
                        } else {
                            throw new Error('删除失败');
                        }
                    })
                    .catch(error => {
                        console.error('删除公告失败:', error);
                        alert('删除失败，请重试！');
                    });
            }
        }
    </script>
</body>

</html>